import re
from rest_framework import serializers

from users.models import User


class AdminSerializer(serializers.ModelSerializer):
    # 管理员序列化器
    class Meta:
        model = User
        fields = '__all__'
        extra_kwargs = {
            'password': {
                'write_only': True,
                'max_length': 20,
                'min_length': 8,
                'required': False
            },
            'username': {
                'max_length': 20,
                'min_length': 5
            }
        }

    def validated_mobile(self, value):
        if not re.match('1[3-9]\d{9}', value):
            raise serializers.ValidationError('手机格式不正确')
        return value

    def create(self, validated_data):
        admin = super().create(validated_data)
        # 密码加密
        admin.set_password(validated_data['password'])
        admin.is_staff = True
        admin.save()
        # 结果返回
        return admin
